﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using Kevin.ChatRoomWCFService.Model;

namespace Kevin.ChatRoomWCFService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "ChatRoomService" in code, svc and config file together.
    public class ChatRoomService : IChatRoomService
    {
        IChatRoomServiceCallBack currentClient = OperationContext.Current.GetCallbackChannel<IChatRoomServiceCallBack>();//当前用户通道

        //用每个用户通道和用户信息组成字典存储当前用户列表，方便查找指定用户通道
        private static Dictionary<string, IChatRoomServiceCallBack> onlineUser = new Dictionary<string, IChatRoomServiceCallBack>();
        private static Dictionary<string, List<StrokeModel>> StrokeModelDic = new Dictionary<string, List<StrokeModel>>();

        public ChatRoomService()
        {
            //通道关闭事件
            OperationContext.Current.Channel.Closing += new EventHandler(Channel_Closing);
        }

        void Channel_Closing(object sender, EventArgs e)
        {

        }

        #region IChatRoomService Members

        public void Login(string userName, string password)
        {
            if (!ChatRoomService.onlineUser.Keys.Contains((userName)))
            {
                ChatRoomService.onlineUser.Add(userName, this.currentClient);
            }

            currentClient.OnLoginComplete();
        }

        public void Logout()
        {
            throw new NotImplementedException();
        }

        public void SaveInkPresenter(StrokeModel strokeModel)
        {
            List<StrokeModel> strokeModelList;

            ChatRoomService.StrokeModelDic.TryGetValue(strokeModel.UserName, out strokeModelList);

            if (strokeModelList != null)
                strokeModelList.Add(strokeModel);
            else
            {
                strokeModelList = new List<StrokeModel>();
                strokeModelList.Add(strokeModel);
            }

            foreach (var key in ChatRoomService.onlineUser.Keys)
            {
                if (key != strokeModel.UserName)
                {
                    if ((ChatRoomService.onlineUser[key] as IContextChannel).State == CommunicationState.Opened)
                        ChatRoomService.onlineUser[key].OnInkStrokesUpdate(strokeModel);
                }
            }
        }

        #endregion
    }
}
